/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */
/**
 * 请求的响应会返回自定义状态码
 *   config['SUCCESS_CODE']  正常请求
 *   config['MESSAGE'] 返回data 里消息
 *   config['REFRESH_CODE']  刷新token
 */

import config   from './config.js';    //配置文件
let _token = config['TOKEN'] || 'access_token'; //token字段
let _refresh_token = config['REFRESH_TOKEN'] || 'refresh_token'; //token字段
const http = {
	//默认配置
	config: {
		baseUrl:config['URL'],
		header: {
			// 'Content-Type':'application/json;charset=UTF-8',
			// 'Content-Type':'application/x-www-form-urlencoded'
		},  
		dataType: "json",
		method:'GET',
		data:{},
		success() {},
		fail() {},
		complete() {},
		configOPT:{},
		interResponse:null,
		interRequest:null
	},
	// 请求
	request(options) {
		// 参数合并
		let url = this.config.baseUrl + options.mod
		options = {
			...this.config,
			...options,
			url
		}
		return new Promise((resolve, reject) => {
			//请求失败
			options.fail = (err) => {
				console.log(err,`！！！-${options.method}-请求失败的err`)
				showToast(config['NETWORK_TIP'])
				reject(err)
			}
			// 请求成功
			options.success = (response) => {
				console.log(response,`>>>-${options.method}-请求成功的response`)
				response.config = _config;
				//请求后的拦截器
				if(options.interResponse){
					options.interResponse(response,resolve,reject)
				}else{
					//没有拦截器直接给结果
					response.statusCode === 200?resolve(response):reject(response); 
				}
			}
			// 用于请求前拦截器 config 参数合并
			let _config = {...options} 
			if (options.interRequest){
				//请求前的拦截器
				options.interRequest(_config,resolve,reject)
			}else{
				//没有请求前拦截 直接发起请求
				wx.request(_config); 
			}
		});
	},	
	get(mod,data={},configOPT = {},options={}) {
		options = {
			header:{
				'Content-Type':'application/x-www-form-urlencoded'
			},
			...options,
			mod,
			data,
			configOPT,
			method:'GET'
		}
		return this.request(options);
	},
	post(mod,data={},configOPT={},options={}) {
		options = {
			header:{
				'Content-Type':'application/json',
			},
			...options,
			mod,
			data,
			configOPT,
			method:'POST'
		}
		return this.request(options)
	},
	uploadFile(options){
		options = {
			formData:{},
			...options,
			url:this.config.baseUrl + options.url,
			interResponse:this.config.interResponse,
			header:{
				'Content-Type':'multipart/form-data',
				...options.header
			}
		}
		return new Promise((resolve,reject)=>{
			//请求失败
			options.fail = (err) => {
				console.log(err,`！！！-文件上传-请求失败的err`)
				showToast(config['NETWORK_TIP'])
				reject(err)
			}
			// 发送成功
			options.success = (response) => {
				console.log(response,`>>>-文件上传-请求成功的response`)
				options.interResponse(response,resolve,reject)
			}

			let token = wx.getStorageSync('userInfo')[_token]
			if(!token){
				goLogin()
				reject({[config['MESSAGE']]:'请登录'})
			}else{
				options.header[_token] = token
				wx.uploadFile(options)
			}
		})
	}
}


//添加请求拦截器
http.config.interRequest = (_config,reject)=>{
	//检查网络环境
	wx.onNetworkStatusChange((res) =>{
	    if(!res.isConnected){
			showToast(config['NETWORK_TIP']);
			return reject({[config['MESSAGE']]:config['NETWORK_TIP']});
		}
	});
	let configOPT = _config['configOPT'] || {};
	// 需要登录
	if(_config.data[_token] || _config.data[_token] == ''){
		//如果没有登录
		if(!wx.getStorageSync('userInfo')[_token]){
			if(configOPT.noGoToLogin)return; //不跳转去登录页
			if(configOPT.navToLogin){goLogin();return;} //不需要重定向跳转登录页
			goLogin('isRedirect');
			return reject({[config['MESSAGE']]:'请登录'});
		}else{
			_config.data[_token] ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5MCJ9.EbbgmPrAzYbIRReRICIRoZUpVos6SX_g7TQHW9aJujw' || wx.getStorageSync('userInfo')[_token]; //如果已登录,将缓存中的token赋值给请求参数
		}
	}
	_config.header[_token] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5MCJ9.EbbgmPrAzYbIRReRICIRoZUpVos6SX_g7TQHW9aJujw'
	_config.data[_token] ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5MCJ9.EbbgmPrAzYbIRReRICIRoZUpVos6SX_g7TQHW9aJujw' || wx.getStorageSync('userInfo')[_token]; //如果已登录,将缓存中的token赋值给请求参数
	return wx.request(_config);
}

//添加响应拦截器
http.config.interResponse = (response,resolve,reject)=>{
	let data = response.data;
	let statusCode = response.statusCode
	if(statusCode !== 200){
		reject(response)
	}else{
		switch (parseInt(data[config['STATUS']])) {
			case config['SUCCESS_CODE']:      // 正常返回
				resolve(response)
				break;
			default:      // 请求参数错误等
			    let message = data[config['MESSAGE']]
				message && showToast(message)
			    reject(data)
				break;
		}
	}
}

function goLogin(isRedirect){
	wx.removeStorageSync('userInfo');
		showToast('请前往登录',()=>{
			if(isRedirect=="isRedirect"){
				wx.redirectTo({
					url: config['LOGIN_URL']
				});
			}else{
				wx.navigateTo({
					url:config['LOGIN_URL']
				})
			}
		})
}
function showToast(title,callback,mask){
	wx.showToast({
		title: title,
		icon: "none",
		position: "bottom",
		mask: mask ||false,
		success() {
			if (typeof callback == "function") {
				setTimeout(function() {
					callback();
				}, 1500)
			}
		}
	})
}
export default http





